package com.itgaoshu.shiroconfig;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: xiyue
 * Date: 2021/3/19
 * Time: 9:22
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Configuration
public class ShiroConfig {
    /**
     * 创建ShiroFilterFactoryBean
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //通过shiro的内置过滤器实现URl的拦截
        /**
         * 常用的过滤器
         * anon:无需认证（登录)也可访问
         * authc:必须认证才可以访问
         * user：使用了remberMe的功能可以访问
         * perms:必须授予资源权限才可以访问
         * role：必须得到资源权限才可以访问
         */
        Map<String,String> filterMap = new LinkedHashMap<String,String>() ;
        filterMap.put("/add.do","authc");
        filterMap.put("/update.do","authc");

        //shiroFilterFactoryBean.setLoginUrl("/index.html");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        shiroFilterFactoryBean.setLoginUrl("/toLogin.do");
        return shiroFilterFactoryBean;

    }

    /**
     * 创建DefaultWebSecurityManager
     * @return
     */
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        //关联Realm
        securityManager.setRealm(realm);
        return  securityManager;

    }
    /**
     * 创建realm
     * @return
     */
    @Bean(name="userRealm")
    public  UserRealm getRealm(){
        return new UserRealm();
    }

}
